package craky.keeper.client;

import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import craky.keeper.bean.KeeperObject;
import craky.keeper.bean.ResultSet;
import craky.keeper.bean.User;
import craky.keeper.util.DBUtil;
import craky.keeper.util.KeeperUtil;
import craky.keeper.view.GlassView;
import craky.keeper.view.KeeperListView;
import craky.keeper.view.ToastView;

public class KeeperActivity extends Activity
{
    private static final String MAIN_PREF_KEY = "main_pref";

    private static final String SHOW_STATUS_BAR = "ShowStatusBar";

    private User user;

    private Resources resources;

    private TextView txtStatus;

    private Button btnAdd;

    private RadioButton btnPay, btnIncome;

    private KeeperListView payList, incomeList;

    private TextView emptyView;

    private OptionsMenuDialog menuDialog;

    private PullDownListener pullDownListener;

    private ToastView toast;

    private GlassView glass;

    private Dialog dialog;

    private boolean isVisitor;

    private long lastBackPressedTime;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_keeper);
        user = KeeperUtil.currentUser;
        resources = getResources();
        txtStatus = (TextView)findViewById(R.id.txtStatus);
        btnAdd = (Button)findViewById(R.id.btnTitleRight);
        payList = (KeeperListView)findViewById(R.id.payList);
        emptyView = (TextView)findViewById(R.id.empty);
        toast = (ToastView)findViewById(R.id.toast);
        glass = (GlassView)findViewById(R.id.glass);
        pullDownListener = new PullDownListener(this);
        txtStatus.setText(user.getName() + "(" + user.getPurviewName() + ")@" + KeeperUtil.currentIp);
        payList.setEmptyView(emptyView);
        emptyView.setOnTouchListener(pullDownListener);
        payList.setPullDownListener(pullDownListener);
        setViewsVisibility();
        loadPreferences();
        payList.post(new Runnable()
        {
            public void run()
            {
                payList.loadDatasFirst();
            }
        });
    }

    @Override
    protected void onPause()
    {
        if(dialog != null)
        {
            dialog.dismiss();
        }

        KeeperListView currentList = getCurrentList();
        currentList.cancelLoad(true);
        currentList.cancelLoadMore();
        pullDownListener.resetHeader();
        savePreferences();
        super.onPause();
    }

    @Override
    public void onBackPressed()
    {
        boolean finish = true;

        if(glass.getVisibility() == View.VISIBLE)
        {
            long current = System.currentTimeMillis();

            if(current - lastBackPressedTime > 2000)
            {
                lastBackPressedTime = current;
                finish = false;
                Toast.makeText(this, R.string.press_again_cancel_and_exit, Toast.LENGTH_SHORT).show();
            }
            else
            {
                getCurrentList().cancelDelete();
            }
        }

        if(finish)
        {
            DBUtil.closeConnection();
            KeeperUtil.remote = null;
            super.onBackPressed();
        }
    }

    public void startOrStopTask(boolean isStart, String errorMessage)
    {
        if(isStart)
        {
            glass.setVisibility(View.VISIBLE);
            toast.startTask(R.drawable.loading, resources.getString(R.string.operating));
        }
        else
        {
            toast.stopTask();
            glass.setVisibility(View.GONE);

            if(errorMessage != null)
            {
                showToast(errorMessage, true);
            }
        }
    }

    public KeeperListView getCurrentList()
    {
        KeeperListView currentList;

        if(isVisitor)
        {
            currentList = payList;
        }
        else
        {
            currentList = btnPay.isChecked()? payList: incomeList;
        }

        return currentList;
    }

    private void loadPreferences()
    {
        SharedPreferences preferences = this.getSharedPreferences(MAIN_PREF_KEY, MODE_PRIVATE);

        if(preferences != null)
        {
            txtStatus.setVisibility(preferences.getBoolean(SHOW_STATUS_BAR, true)? View.VISIBLE: View.GONE);
        }
    }

    private void savePreferences()
    {
        SharedPreferences preferences = this.getSharedPreferences(MAIN_PREF_KEY, MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(SHOW_STATUS_BAR, txtStatus.getVisibility() == View.VISIBLE? true: false);
        editor.commit();
    }

    private void setViewsVisibility()
    {
        ((ImageView)findViewById(R.id.titleLogo)).setVisibility(View.VISIBLE);

        if(user.getPurview() < User.VISITOR)
        {
            incomeList = (KeeperListView)findViewById(R.id.incomeList);
            incomeList.setPay(false);
            incomeList.setEmptyView(emptyView);
            incomeList.setPullDownListener(pullDownListener);
            btnAdd.setText(resources.getString(R.string.add));
            btnAdd.setVisibility(View.VISIBLE);
            ((RadioGroup)findViewById(R.id.buttonGroup)).setVisibility(View.VISIBLE);
            initTabsAction();
        }
        else
        {
            isVisitor = true;
            ((TextView)findViewById(R.id.txtTitle)).setVisibility(View.VISIBLE);
        }
    }

    private void initTabsAction()
    {
        btnPay = (RadioButton)findViewById(R.id.btnPay);
        btnIncome = (RadioButton)findViewById(R.id.btnIncome);
        TitleTabSwitcher tabSwitcher = new TitleTabSwitcher(this, btnPay, btnIncome, payList, incomeList, emptyView, pullDownListener);
        btnPay.setOnCheckedChangeListener(tabSwitcher);
        btnIncome.setOnCheckedChangeListener(tabSwitcher);
    }

    public void switchMenuButtonText(Button button)
    {
        if(txtStatus.getVisibility() == View.VISIBLE)
        {
            button.setText(resources.getString(R.string.hide_status_bar));
        }
        else
        {
            button.setText(resources.getString(R.string.show_status_bar));
        }
    }

    public void switchStatusBar()
    {
        if(txtStatus.getVisibility() == View.VISIBLE)
        {
            txtStatus.setVisibility(View.GONE);
        }
        else
        {
            txtStatus.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menuDialog = new OptionsMenuDialog(this);
        return true;
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu)
    {
        FragmentManager fm = this.getFragmentManager();
        menuDialog.show(fm, null);
        return false;
    }

    @Override
    public void onOptionsMenuClosed(Menu menu)
    {
        super.onOptionsMenuClosed(menu);
        menuDialog.dismiss();
    }

    public void showToast(String message, boolean isError)
    {
        toast.showToast(isError? R.drawable.toast_icon_w: R.drawable.success, message);
    }

    public void onTitleRightClick(View view)
    {
        getCurrentList().addItem();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if(resultCode == KeeperUtil.RESULT_CODE_OK)
        {
            ResultSet resultSet = (ResultSet)data.getSerializableExtra(KeeperUtil.KEY_KEEPER_DATA);
            boolean isPay = data.getBooleanExtra(KeeperUtil.KEY_IS_PAY, true);
            KeeperObject keeperData = isPay? resultSet.getPay(): resultSet.getIncome();
            KeeperListView listView = this.getCurrentList();
            final StringBuilder info = new StringBuilder();

            if(resultSet.getOldUpdateTime() == listView.getLastUpdateTime())
            {
                listView.setLastUpdateTime(resultSet.getLastUpdateTime());
            }

            switch(requestCode)
            {
                case KeeperUtil.REQUEST_CODE_ADD:
                {
                    info.append(resources.getString(R.string.add_success));
                    listView.refreshViewData(keeperData, true);
                    break;
                }
                case KeeperUtil.REQUEST_CODE_MODIFY:
                {
                    info.append(resources.getString(R.string.modify_success));
                    listView.refreshViewData(keeperData, false);
                    break;
                }
            }

            if(info.length() > 0)
            {
                listView.postDelayed(new Runnable()
                {
                    public void run()
                    {
                        showToast(info.toString(), false);
                    }
                }, 300);
            }
        }
    }

    public Dialog getDialog()
    {
        return this.dialog;
    }

    public void setDialog(Dialog dialog)
    {
        this.dialog = dialog;
    }
}